//
//  ViewController.swift
//  AG_Test
//
//  Created by AG on 2020/12/2.
//

import UIKit
import SnapKit

class ViewController: UIViewController, UITextViewDelegate {
    
    private let textPlaceHolder = "写点什么吧~"
    private let urlStr = "https://api.github.com/"
    var timer: Timer?
    var textView: UITextView = UITextView()
    var dataArray = [Any]()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setRightNavbar()
        self.createLabel()
        self.createTextView()
        self.getDefaultData()
        
        self.timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(createNetRequest), userInfo: nil, repeats: true)
    }
    
    func createLabel() {
        let label = UILabel()
        label.text = "URL: \(self.urlStr)"
        label.font = UIFont.systemFont(ofSize: 14)
        self.view.addSubview(label)
        label.snp.makeConstraints { (make) in
            make.left.top.equalToSuperview().offset(15)
            make.right.equalToSuperview().inset(15)
            make.height.equalTo(16)
        }
    }
    
    func createTextView() {
        let space : CGFloat = 15
        let textH : CGFloat = 50
        textView.textAlignment = .left
        textView.delegate = self
        textView.text = self.textPlaceHolder
        textView.keyboardType = .default
        textView.isUserInteractionEnabled = true
        textView.font = UIFont.systemFont(ofSize: 14)
        textView.textColor = UIColor.black
        textView.backgroundColor = UIColor.clear
        textView.layer.borderWidth = 0.5
        textView.layer.borderColor = UIColor.gray.cgColor
        self.view.addSubview(textView)
        
        textView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(space)
            make.right.equalToSuperview().inset(space)
            make.top.equalToSuperview().offset(40)
            make.bottom.equalToSuperview().inset(textH)
        }
    }
    
    func setRightNavbar() {
        let rightBar = UIBarButtonItem(title: "历史记录", style: .plain, target: self, action: #selector(goToHistory))
        self.navigationItem.rightBarButtonItems = [rightBar]
    }
    
    @objc func goToHistory() {
        let vc = AGNetRequestHistoryVC.init()
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @objc func createNetRequest() {
        
        let date = Date()
        let formatter = DateFormatter()
        formatter.locale = Locale.init(identifier: "zh_CN")
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let dateStr = formatter.string(from: date)
        
        var dataDic = [String: Any]()
        dataDic["date"] = dateStr
        
        let url = URL(string: self.urlStr)
        let session: URLSession = URLSession.shared
        let request: URLRequest = URLRequest(url: url!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 3)
        let dask: URLSessionDataTask = session.dataTask(with: request) { (data, response, error) in
            if((error == nil)) {
                do {
                    let dict  = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)
                    DispatchQueue.main.async {
                        self.textView.text = "\(dict)"
                    }
                    dataDic["content"] = dict
                    self.saveData(dic: dataDic)
                    
                } catch {
                    
                }
            } else {
                if let err = error as NSError? {
                    DispatchQueue.main.async {
                        self.textView.text = "\(err.userInfo)"
                    }
                    dataDic["content"] = err.userInfo
                    self.saveData(dic: dataDic)
                }
            }
        }
        dask.resume()
    }
    
    func saveData(dic:[String: Any]) {
        var index = UserDefaults.standard.integer(forKey: "index")
        if self.dataArray.count >= 50 {
            self.dataArray .removeAll()
            index += 1
            UserDefaults.standard.set(index, forKey: "index")
            UserDefaults.standard.synchronize()
        }
        self.dataArray.append(dic)
        
        let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let archiveURL = documentDirectory.appendingPathComponent("hisdory_\(index).plist")
        do {
            let data = try NSKeyedArchiver.archivedData(withRootObject: self.dataArray, requiringSecureCoding: true)
            try data.write(to: archiveURL)
        } catch {
            print("写入data数据失败: \(error)")
        }
    }
    
    func getDefaultData() {
        let index = UserDefaults.standard.integer(forKey: "index")
        if index == 0 {
            UserDefaults.standard.set(1, forKey: "index")
            UserDefaults.standard.synchronize()
        } else {
            let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
            let archiveURL = documentDirectory.appendingPathComponent("hisdory_\(index).plist")
            do {
                let data = try Data.init(contentsOf: archiveURL)
                let obj = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data)
                if let arr = obj as? [Any]  {
                    if let dic = arr.last as? [String: Any] {
                        self.textView.text = "\(dic)"
                    }
                }
            } catch {
                print("获取data数据失败: \(error)")
            }
        }
    }
    
    
    
    
    
}

